package com.syyo.sso.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @ author: wang
 * @ date: 2021/4/19 9:40
 * @ Description:
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 登录接口
     *
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 把登录成功的用户保存起来
            redisTemplate.opsForValue().set(uuid, username);

            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);

            //登录成功，跳回到之前的登录页
            return "redirect:" + url + "?token=" + uuid;
        }

        //登录失败，跳回登录页
        return "login";

    }

    /**
     * 登录页
     *
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
                            Model model,
                            @CookieValue(value = "sso_token", required = false) String token) {

        if (!StringUtils.isEmpty(token)) {
            // 有cookie，说明有人登录
            //登录成功，跳回到之前的登录页
            return "redirect:" + url + "?token=" + token;
        }

        model.addAttribute("url", url);
        //登录成功，跳回到之前的登录页
        return "login";

    }

    /**
     * 登录接口
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/info")
    public String info(@RequestParam("token") String token) {

        //  查询登录用户
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }
}
